<?php

namespace user\Controller;

use core\App;

class LoginController extends UserAppController
{
    protected $arrayDataUser = array();
    protected $arrayLogin = array();
    protected $arrayPermission = array();

    public function beforeFilter(){
        $this->startSessionSystem();
    }

    public function indexAction()
    {
        if($this->Session->is('SYSTEM.LOCAL')) {
            $redirectAction = $this->Session->read('SYSTEM.LOCAL');
            $this->redirect(array('action' => $redirectAction));
        }
        else
        {
            $this->redirect(array('url' => $this->getUrl()));
        }
    }

    public function unimedAction()
    {
        $this->set('data',$this->request->data);
        if($this->request->is('post'))
        {
            if($this->_model->isValidate($this->request->data))
            {
                $this->request->data['senha'] = $this->hash($this->request->data['senha']);
                if ($this->_model->authentic($this->request->data))
                {
                    if($this->_model->primeiro_acesso){
                        $this->startSession(2);
                        $this->redirect(array('action' => 'createPasswordUser'));
                    }else{
                        $this->startSession(true);
                        $module = $this->Session->read('authe.USER.GROUP.MODULE_PRIMARY_PATH');
                        $this->redirect(array('action' => 'index', 'controller' => 'index', 'module' => $module));
                    }
                }
                else
                {
                    $this->Session->setFlash($this->msgType("login"), "warning");
                }
            }
            $this->returnMsg($this->_model->getMessage());
        }
        if($this->Session->is('authe.URL'))
        {
            $this->redirect(array('module' => $this->Session->read('authe.URL.MODULE_PRIMARY'), 'controller' => 'index'));
        }
        $this->set("schema", "Unimed");
        $this->set("logo", "unimed.jpg");
        $this->set("bg_color", "green");
        $this->render('login');
    }

    public function intermedAction()
    {
        $this->set('data',$this->request->data);
        if($this->request->is('post'))
        {
            if($this->_model->isValidate($this->request->data))
            {
                $this->request->data['senha'] = $this->hash($this->request->data['senha']);
                if ($this->_model->authentic($this->request->data))
                {
                    if($this->_model->primeiro_acesso){
                        $this->startSession(2);
                        $this->redirect(array('action' => 'createPasswordUser'));
                    }else{
                        $this->startSession(true);
                        $module = $this->Session->read('authe.USER.GROUP.MODULE_PRIMARY_PATH');
                        $this->redirect(array('action' => 'index', 'controller' => 'index', 'module' => $module));
                    }
                }
                else
                {
                    $this->Session->setFlash($this->msgType("login"), "warning");
                }
            }
            $this->returnMsg($this->_model->getMessage());
        }

        if($this->Session->is('authe.URL'))
        {
            $this->redirect(array('module' => $this->Session->read('authe.URL.MODULE_PRIMARY'), 'controller' => 'index'));
        }
        $this->set("schema", "Intermed");
        $this->set("logo", "intermed.png");
        $this->set("bg_color", "bg-gray");
        $this->render('login');
    }

    public function createPasswordUserAction(){

        $this->set('data',$this->request->post());
        if($this->request->is('post')){
            if($this->_model->isValidate($this->request->post()))
            {
                $this->request->post('senha',$this->hash($this->request->post('new_password')));
                if($this->_model->updatePass($this->request->post()))
                {
                    $this->startSession(true);
                    $module = $this->Session->read('authe.USER.GROUP.MODULE_PRIMARY_PATH');
                    $this->redirect(array('action' => 'index', 'controller' => 'index', 'module' => $module));
                }else{
                    $this->Session->setFlash($this->msgType("error"), "danger");
                    $this->redirect(array('action' => 'createPasswordUser'));
                }
            }
            $this->returnMsg($this->_model->getMessage());

        }
        $this->render('create_password_user');

    }

    public function logoutAction(){
        $redirectAction = $this->Session->read('SYSTEM.LOCAL');
        $this->Session->delete('authe');
        $this->redirect(array('action'=>$redirectAction,'controller'=>$this->controller,'module'=>'user'));
        return false;
    }

    protected function startSession($start=false){
        $dados = $this->sessionUser();
        $dados['AUTHENTICATED'] = $start;
        $this->Session->session($dados,'authe');
        return true;
    }

    protected function sessionUser()
    {
        $result = $this->_model->dataPermission();
        $this->arrayPermission['MODULE'] = '';
        $path_modulo_principal = $this->_model->dataUser()->NOME_MODULO;
        foreach($result as $value){
            $nome_usuario = preg_split('/\s/',$value->NOME);
            $nome_usuario = (count($nome_usuario) > 1) ? $nome_usuario[0] . " " . $nome_usuario[1] : $nome_usuario[0];
            $this->arrayLogin['USER']['USUARIO_ID'] = $value->USUARIO_ID;
            $this->arrayLogin['USER']['CARGO_ID'] = $value->CARGOS_ID;
            $this->arrayLogin['USER']['SETOR_ID'] = $value->SETORES_ID;
            $this->arrayLogin['USER']['LOGIN'] = $value->LOGIN;
            $this->arrayLogin['USER']['NOME'] = $nome_usuario;
            $this->arrayLogin['USER']['NOME_COMPLETO'] = $value->NOME;
            $this->arrayLogin['USER']['FOTO'] = $value->FOTO;
            $this->arrayLogin['USER']['GROUP']['ID'] = $value->GRUPO_USUARIO_ID;
            $this->arrayLogin['USER']['GROUP']['NOME_GRUPO'] = $value->GUDESCRICAO;
            $this->arrayLogin['USER']['GROUP']['MODULE_PRIMARY_ID'] = $value->MODULO_PRINCIPAL;
            $this->arrayLogin['USER']['GROUP']['MODULE_PRIMARY_PATH'] = $path_modulo_principal;
            $this->arrayLogin['URL']['MODULE_PRIMARY'] = $path_modulo_principal;
            $action = null;
            if($value->STATUS_PERMISSAO == 1){
                $action = $value->ACTION;
            }
            $this->arrayPermission['MODULE'][strtolower($value->NOME_MODULO)]['CONTROLLER'][$value->NOME_CONTROLLER]['ACTION'][] = $action;
        }
        $this->arrayLogin['USER']['PERMISSION'] = $this->arrayPermission;
        return $this->arrayLogin;
    }

}